﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using ShareMarking.Service;
using ShareMarking.Entity;

namespace ShareMarking.ShowqrCode
{
    /// <summary>
    /// api 的摘要说明
    /// </summary>
    public class api : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var method = ComLib.QueryStringHelper.GetFormString("method");
            switch (method)
            {
                case "gethospqrlist":
                    gethospqrlist(context);
                    break;
                case "getpnrqrlist":
                    getpnrqrlist(context);
                    break;
                default:
                    //context.Response.ContentType = "application/json";
                    context.Response.Write("{\"subcode\":\"05\",\"msg\":\"请求方法错误\",\"result\":{}}");
                    break;
            }
        }

        private void gethospqrlist(HttpContext context)
        {
            try
            {
                ComLib.LogLib.Log4NetBase.Log("1、同步HOSP二维码请求到达");
                var access_id = ComLib.QueryStringHelper.GetFormString("access_id");
                var method = ComLib.QueryStringHelper.GetFormString("method");
                var timestamp = ComLib.QueryStringHelper.GetFormString("timestamp");
                var sign = ComLib.QueryStringHelper.GetFormString("sign");

                #region 开始签名认证
                if (access_id.IsNullOrEmpty())
                {
                    context.Response.Write("{\"subcode\":\"02\",\"msg\":\"用户错误\",\"result\":{}}");
                }
                else
                {
                    #region 签名
                    var parameters = new Dictionary<string, string>();
                    parameters.Add("access_id", access_id);
                    parameters.Add("method", method);
                    parameters.Add("timestamp", timestamp);

                    var request_str = BuildQuery(parameters);
                    var signature = HMACSHA1Encrypt(request_str, "accessuser_secret_sfa");
                    ComLib.LogLib.Log4NetBase.Log("1-2、签名请求参数:::::::::::access_id=" + access_id + "//method=" + method + "//timestamp=" + timestamp + "//sign=" + sign + "最终组合参数：" + request_str);
                    #endregion

                    if (sign == signature)
                    {
                        #region 组装返回
                        var ds = qr_QrCodeRelateService.Instance.db.From<qr_QrCodeRelate>()
                            .InnerJoin<qr_QrCode>(qr_QrCodeRelate._.qr_Scene_ID == qr_QrCode._.scene_id)
                            .Where(qr_QrCodeRelate._.qr_Type == 2).ToDataSet();

                        results results = new ShowqrCode.results();
                        results.subcode = "00";
                        results.msg = "成功";

                        List<hosp> alist = new List<hosp>();
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            hosp hosp = new hosp()
                            {
                                hospid = ds.Tables[0].Rows[i]["rel_Code"].ToString(),
                                hospname = ds.Tables[0].Rows[i]["title"].ToString(),
                                code_url = ds.Tables[0].Rows[i]["code_url"].ToString(),
                                qrcode_url = ds.Tables[0].Rows[i]["qrcode_url"].ToString(),
                            };
                            alist.Add(hosp);
                        }
                        result result = new ShowqrCode.result()
                        {
                            countNum = ds.Tables[0].Rows.Count.ToString(),
                            alist = alist
                        };
                        results.result = result;
                        #endregion

                        string re = ComLib.JsonHelper.JsonSerializer<results>(results);
                        context.Response.Write(re);
                        ComLib.LogLib.Log4NetBase.Log("1-3、返回医院二维码数据:条数:" + alist.Count);
                        //    context.Response.Write("{\"subcode\":\"00\",\"msg\":\"成功\",\"result\":{\"countNum\":\"1\",\"alist\":[{\"hospid\":\"1\",\"hospname\":\"广州人民医院\",\"code_url\":\"\",\"qrcode_url\":\"\"}]}}");
                    }
                    else
                    {
                        context.Response.Write("{\"subcode\":\"03\",\"msg\":\"签名失败\",\"result\":{}}");
                        ComLib.LogLib.Log4NetBase.Log("1-3、同步医院数据错误，签名失败:::::" + "请求的签名：" + sign + ":::::" + "本地签名：" + signature);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log(ex.Message + ex.StackTrace);
            }
        }

        private static void getpnrqrlist(HttpContext context)
        {
            ComLib.LogLib.Log4NetBase.Log("2、同步PNR二维码");
            var access_id = ComLib.QueryStringHelper.GetFormString("access_id");
            var method = ComLib.QueryStringHelper.GetFormString("method");
            var timestamp = ComLib.QueryStringHelper.GetFormString("timestamp");
            var sign = ComLib.QueryStringHelper.GetFormString("sign");

            #region 开始签名认证
            if (access_id.IsNullOrEmpty())
            {
                context.Response.Write("{\"subcode\":02,\"msg\":\"用户不存在\",\"result\":{}}");
            }
            else
            {
                var parameters = new Dictionary<string, string>();
                parameters.Add("access_id", access_id);
                parameters.Add("method", method);
                parameters.Add("timestamp", timestamp);

                var request_str = BuildQuery(parameters);
                var signature = HMACSHA1Encrypt(request_str, "accessuser_secret_sfa");
                ComLib.LogLib.Log4NetBase.Log("2-2、签名请求参数:::::::::::access_id=" + access_id + "//method=" + method + "//timestamp=" + timestamp + "//sign=" + sign + "//最终组合参数：" + request_str);
                if (sign == signature)
                {
                    #region 组装返回
                    var ds = qr_QrCodeRelateService.Instance.db.From<qr_QrCodeRelate>()
                        .InnerJoin<qr_QrCode>(qr_QrCodeRelate._.qr_Scene_ID == qr_QrCode._.scene_id)
                        .Where(qr_QrCodeRelate._.qr_Type == 3).ToDataSet();

                    ShareMarking.ShowqrCode_ext.results results = new ShareMarking.ShowqrCode_ext.results();
                    results.subcode = "00";
                    results.msg = "成功";

                    List<pnr> alist = new List<pnr>();
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        pnr pnr = new pnr()
                        {
                            pnrid = ds.Tables[0].Rows[i]["rel_Code"].ToString(),
                            pnrname = ds.Tables[0].Rows[i]["title"].ToString(),
                            code_url = ds.Tables[0].Rows[i]["code_url"].ToString(),
                            qrcode_url = ds.Tables[0].Rows[i]["qrcode_url"].ToString(),
                        };
                        alist.Add(pnr);
                    }
                    ShareMarking.ShowqrCode_ext.result result = new ShareMarking.ShowqrCode_ext.result()
                    {
                        countNum = ds.Tables[0].Rows.Count.ToString(),
                        alist = alist
                    };
                    results.result = result;
                    #endregion

                    string re = ComLib.JsonHelper.JsonSerializer<ShareMarking.ShowqrCode_ext.results>(results);
                    context.Response.Write(re);
                    ComLib.LogLib.Log4NetBase.Log("2-3、同步PNR二维码返回数据:条数:" + alist.Count);
                    //context.Response.Write("{\"subcode\":\"00\",\"msg\":\"成功\",\"result\":{\"countNum\":\"1\",\"alist\":[{\"pnrid\":\"1\",\"pnrname\":\"张为民\",\"code_url\":\"\",\"qrcode_url\":\"\"}]}}");
                }
                else
                {
                    context.Response.Write("{\"subcode\":\"03\",\"msg\":\"签名失败\",\"result\":{}}");
                    ComLib.LogLib.Log4NetBase.Log("2-3、同步PNR数据错误，签名失败:::::" + "请求的签名：" + sign + ":::::" + "本地签名：" + signature);
                }
            }
            #endregion
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public static string BuildQuery(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名为空的参数
                if (!string.IsNullOrEmpty(name))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(HttpUtility.UrlEncode(name, Encoding.UTF8));
                    postData.Append("=");
                    postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    hasParam = true;
                }
            }

            return postData.ToString();
        }

        public static string HMACSHA1Encrypt(string EncryptText, string EncryptKey)
        {
            HMACSHA1 hmacsha1 = new HMACSHA1();
            hmacsha1.Key = Encoding.UTF8.GetBytes(EncryptKey);
            byte[] dataBuffer = Encoding.UTF8.GetBytes(EncryptText);
            byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
            return Convert.ToBase64String(hashBytes);
        }
    }

    public class results
    {
        public string subcode;
        public string msg;
        public result result;
    }
    public class result
    {
        public string countNum;
        public List<hosp> alist;
    }

    public class hosp
    {
        public string hospid;
        public string hospname;
        public string code_url;
        public string qrcode_url;
    }

    public class pnr
    {
        public string pnrid;
        public string pnrname;
        public string code_url;
        public string qrcode_url;
    }
}

namespace ShareMarking.ShowqrCode_ext
{
    public class results
    {
        public string subcode;
        public string msg;
        public result result;
    }

    public class result
    {
        public string countNum;
        public List<ShareMarking.ShowqrCode.pnr> alist;
    }
}